/*
 * Project: yygh-parent
 *
 * File Created at 2023/9/3
 *
 * 自定义时间格式代替DATE标签：2023-09-03 18:59:18:59
 */
package com.atguigu.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;

import com.atguigu.constant.MqConst;
import com.atguigu.yygh.HospitalFeignClient;
import com.atguigu.yygh.PatientFeignClient;
import com.atguigu.yygh.common.exception.HospitalException;
import com.atguigu.yygh.common.helper.HttpRequestHelper;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderMapper;
import com.atguigu.yygh.order.service.*;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 用户名
 * @Type OrderServiceImpl.java
 * @Desc
 * @date 2023/9/3 18:59
 */
@Service
public class OrderServiceImpl extends
        ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {

    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private RefundInfoService refundInfoService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OrderMapper orderMapper;


    /**
     * @Description 得到订单需要的数据,然后向订单数据库保存数据,同时向管理端数据库保存
     * @author jams
     * @version 1.17.0
     * @date 2023/9/8 18:35
     */
    @Override
    public Long saveOrder(String scheduleId, Long userId) {
        //通过patientId得到病人信息
        //Patient(userId=22, name=江首, certificatesType=10, certificatesNo=441402199912160255, sex=1, birthdate=Mon Jul 31 00:00:00 CST 2023, phone=18927939204, isMarry=0, provinceCode=110000, cityCode=110100, districtCode=110101, address=华夏, contactsName=, contactsCertificatesType=, contactsCertificatesNo=, contactsPhone=, isInsure=0, cardNo=null, status=0)
        Patient patient = patientFeignClient.getPatient(userId);
//        if (patient==null){
//            throw new HospitalException(ResultCodeEnum.FETCH_USERINFO_ERROR);
//        }
        System.out.println(patient);
        //通过scheduleId得到schedule信息
        Result scheduleByScheduleId = hospitalFeignClient.getScheduleByScheduleId(scheduleId);


        Object data = scheduleByScheduleId.getData();
        String s = JSONObject.toJSONString(data);
        Schedule schedule = JSONObject.parseObject(s, Schedule.class);
        if (schedule==null){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        if(schedule.getAvailableNumber()<=0){
            throw new HospitalException(ResultCodeEnum.NUMBER_NO);
        }

        //如果未到预约时间就抛出异常
        Date date1 = new Date();
        boolean beforeNow = new DateTime(schedule.getWorkDate()).isBeforeNow();
        if (!beforeNow){
            throw  new HospitalException(ResultCodeEnum.TIME_NO);
        }


        //整合信息为orderInfo对象,更新数据库
        OrderInfo orderInfo = new OrderInfo();
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(schedule.getHoscode());


        Map<String, Object> param = schedule.getParam();

//        Result(code=200, message=成功, data={id=64c4f763bc729e5fcc3bf7b7, createTime=2023-07-29 19:26:27, updateTime=2023-07-29 19:26:27, isDeleted=0, param={depname=多发性硬化专科门诊, hosname=人民医院}, hoscode=1000_0, depcode=200040878, title=医师, docname=邵迎红, skill=内分泌科常见病。, workDate=2020-12-13, workTime=0, reservedNumber=33, availableNumber=22, amount=100, status=0, hosScheduleId=1})
//        Schedule(hoscode=1000_0, depcode=200040878, title=医师, docname=邵迎红, skill=内分泌科常见病。, workDate=Sun Dec 13 00:00:00 CST 2020, workTime=0, reservedNumber=33, availableNumber=22, amount=100, status=0, hosScheduleId=1)
//        OrderInfo(userId=null, outTradeNo=null, hoscode=null, hosname=null, depcode=null, depname=null, scheduleId=null, title=null, reserveDate=null, reserveTime=null, patientId=null, patientName=null, patientPhone=null, hosRecordId=null, number=null, fetchTime=null, fetchAddress=null, amount=null, quitTime=null, orderStatus=null)
        BeanUtils.copyProperties(schedule,orderInfo);
        BeanUtils.copyProperties(patient,orderInfo);

        String depname = param.get("depname").toString();
        String hosname = param.get("hosname").toString();
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setDepname(depname);
        orderInfo.setHosname(hosname);
        orderInfo.setUserId(userId);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setHoscode(schedule.getHoscode());
        orderInfo.setDepcode(schedule.getDepcode());
        orderInfo.setReserveDate(schedule.getWorkDate());
        orderInfo.setUpdateTime(new Date());
        //设置上下午
        orderInfo.setReserveTime(dayOrNight(schedule.getWorkDate()));
        orderInfo.setPatientId(patient.getId());
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        //取号时间,就是预约时间之前1个小时
        Date workDate = schedule.getWorkDate();
        DateTime dateTime=new DateTime(workDate);
        int hourOfDay = dateTime.getHourOfDay();
        dateTime.plusHours(-1);
        String s1 = dateTime.toString();
        orderInfo.setFetchTime(s1);
        orderInfo.setFetchAddress(schedule.getHoscode()+"一楼数字打印机");
        //退号时间在预约的前一天
        workDate.setHours(00);
        DateTime dateTime1=new DateTime(workDate);
        dateTime.minusDays(1);
        Date date = dateTime.toDate();

        orderInfo.setQuitTime(date);

        //需要算出预约号码数,预约数-1 hosp
        Integer availableNumber = schedule.getAvailableNumber();
        int  newAvailableNumber= availableNumber.intValue()-1;
        //预约号加1
        Integer reservedNumber = schedule.getReservedNumber();
        int newReservedNumber = reservedNumber.intValue()+1;
        Schedule schedule1 = new Schedule();
        BeanUtils.copyProperties(schedule,schedule1);
        //更新后的schedule
        schedule1.setAvailableNumber(newAvailableNumber);
        schedule1.setReservedNumber(newReservedNumber);




        //设置订单状态为为等待支付
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());

        //order保存,相当于更新和保存一起,由feign改为mq保存
//        Result result = hospitalFeignClient.saveSchedule(schedule1);

//        if (result.getCode()!=200){
//            throw new HospitalException(ResultCodeEnum.FAIL);
//
//        }
//        System.out.println(result);
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setAvailableNumber(schedule1.getAvailableNumber());
        orderMqVo.setReservedNumber(schedule1.getReservedNumber());
        orderMqVo.setScheduleId(schedule1.getId());
        //短信提示
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        msmVo.setTemplateCode("SMS_194640721");
        String reserveDate =
                new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                        + (orderInfo.getReserveTime()==0 ? "上午": "下午");
        Map<String,Object> param1 = new HashMap<String,Object>(){{
            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            put("amount", orderInfo.getAmount());
            put("reserveDate", reserveDate);
            put("name", orderInfo.getPatientName());
            put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
        }};
        msmVo.setParam(param1);

        orderMqVo.setMsmVo(msmVo);

        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

        System.out.println(orderInfo);

        //向管理系统插入数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("patient_id",patient.getId());
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        //这个orderinfo是在mongodb中的字符串id,schedule得到数据库的id
        paramMap.put("hosScheduleId",schedule.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());


        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        JSONObject result1 = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl()+"/order/submitOrder");
        if(result1.getInteger("code") == 200) {
            JSONObject jsonObject = result1.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            orderInfo.setUpdateTime(new Date());
            DateTime dateTime2 = new DateTime();

            //sou
            baseMapper.insert(orderInfo);

            //排班可预约数
            Integer reservedNumber1 = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber1 = jsonObject.getInteger("availableNumber");
            //发送mq信息更新号源和短信通知
            


        }else{

            throw new HospitalException(result1.getString("message"), ResultCodeEnum.FAIL.getCode());
        }





        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        OrderInfo orderInfo1 = this.packOrderInfo(orderInfo);
        return orderInfo1;
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(patientId!=null) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        //判空
        //判断是否已经支付
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //超过可退款的时间
        DateTime dateTime = new DateTime(orderInfo.getQuitTime());
        if(dateTime.isAfterNow()){
                throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_NO);
        }

        //更新管理系统的
        // 调用医院接口，通知更新支付状态
        SignInfoVo signInfoVo
                = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        //TODO
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());

        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");
        if(result.getInteger("code") != 200) {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }


        //订单已经被支付,退款
        if (orderInfo.getOrderStatus()==OrderStatusEnum.PAID.getStatus()){
                  //TODO.并且更新支付状态
            boolean refund = weixinService.refund(orderId);
            if (refund==false){
                throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_FAIL);
            }
        }
        //MQ: 更新可预约订单数量,短信通知


        //没有被支付直接取消订单
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);

        /**
         * @Description  调用MQ的monogo更新Schedule
         * @author jams
         * @version 1.17.0
         * @date 2023/10/1 19:20
         */
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
//短信提示到Order
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        msmVo.setTemplateCode("SMS_462405825");
        String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
        Map<String,Object> param = new HashMap<String,Object>(){{
            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            put("reserveDate", reserveDate);
            put("name", orderInfo.getPatientName());
        }};
        msmVo.setParam(param);
        orderMqVo.setMsmVo(msmVo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

        //**end

        //记录到退款表中,需要先得到paymentInfo的id
        PaymentInfo payment = paymentService.getByOutTradeNo(orderInfo.getOutTradeNo());
        refundInfoService.saveRefundInfo(payment);

        //向管理系统更新schedule信息

        return true;
    }
    
    /** 
     * @Description  定时任务短信提醒
     * @author jams
     * @version 1.17.0 
     * @date 2023/10/2 18:47
     */
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for(OrderInfo orderInfo : orderInfoList) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        Map<String, Object> map = new HashMap<>();

        List<OrderCountVo> orderCountVoList
                = orderMapper.selectOrderCount(orderCountQueryVo);
        //日期列表
        List<String> dateList
                =orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList
                =orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    //设置上下午
    public static int dayOrNight(Date date){
        DateTime dateTime = new DateTime(date);
        int hourOfDay = dateTime.getHourOfDay();
        if (hourOfDay>12){
            return 1;
        }else {
            return 0;
        }


    }


}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * <p>
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2023/9/3 用户名 create
 */ 
